package com.sharding.controller;

import cn.hutool.core.util.RandomUtil;
import com.jiao.datasource.parse.SQLStruct;
import com.jiao.table.cache.DynamicCacheRead;
import com.jiao.table.exception.WriteCacheInfoException;
import com.sharding.entity.PersionVO;
import com.sharding.entity.Person;
import com.sharding.service.PersonService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description
 * @Author Vincent.jiao
 * @Date 2022/5/19 14:30
 */
@Controller
@RequestMapping("dataSource")
public class DataSourceController {
    @Autowired
    DataSource dataSource;

    @Autowired
    PersonService personService;

    @SneakyThrows
    public Connection getConn() {
       return dataSource.getConnection();
    }

    @SneakyThrows
    @RequestMapping("batchAdd")
    @ResponseBody
    public Object batchAdd(String name){
        Connection conn = getConn();
        PreparedStatement ps = conn.prepareStatement(" insert into person (p_name, p_sex, p_card_id,  p_explain) values (?, ?, ?, ?) ");
        for (int i = 0; i < 3; i++) {
            ps.setString(1, name + " "+i);
            ps.setInt(2, RandomUtil.randomInt(2));
            ps.setString(3, RandomUtil.randomInt(1000000) + "");
            ps.setString(4, RandomUtil.randomString(10));

            ps.addBatch();
        }

        ps.executeUpdate();

        conn.close();
        return "OK";
    }

    @SneakyThrows
    @RequestMapping("batchUpdate")
    @ResponseBody
    public Object batchUpdate(){
        List<Person> list = personService.getAll();

        Connection conn = getConn();
        PreparedStatement ps = conn.prepareStatement(" update person  set p_name = ?,\n" +
                "      p_sex = ?, \n" +
                "      p_card_id = ?, \n" +
                "      p_explain = ? \n" +
                "    where p_id = ? ");
        for (int i = 0; i < 3; i++) {
            Person person = list.get(RandomUtil.randomInt(list.size() - 1));
            ps.setString(1, person.getP_id() + "jiaojiao");
            ps.setInt(2, RandomUtil.randomInt(2));
            ps.setString(3, RandomUtil.randomInt(1000000) + "");
            ps.setString(4, RandomUtil.randomString(10));
            ps.setLong(5, person.getP_id());

            ps.addBatch();
        }

        ps.executeUpdate();

        conn.close();
        return "OK";
    }

}
